import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:developer' as developer;

import 'index.dart';
import 'widgets/delete_friend_dialog.dart';
import '../../../common/utils/toast_util.dart';

class MessageChatPage extends StatelessWidget {
  const MessageChatPage({super.key});
  
  // 🔥 获取控制器tag - 确保与controller.dart中的逻辑完全一致
  String _getControllerTag() {
    String chatUserId = 'unknown';
    
    if (Get.arguments != null) {
      if (Get.arguments is ChatUser) {
        chatUserId = (Get.arguments as ChatUser).id;
      } else if (Get.arguments is Map<String, dynamic>) {
        final args = Get.arguments as Map<String, dynamic>;
        chatUserId = args['userId']?.toString() ?? '';
      }
    }
    
    return "message_chat_$chatUserId";
  }

  
  // 🔥 新架构：判断是否应该显示时间戳（用于Map格式的消息）
  bool _shouldShowTimestamp(int index, List<Map<String, dynamic>> messages) {
    if (index == 0) return true; // 第一条消息总是显示时间
    
    final currentTimestamp = DateTime.fromMillisecondsSinceEpoch(
      messages[index]['timestamp'] ?? DateTime.now().millisecondsSinceEpoch,
    );
    final previousTimestamp = DateTime.fromMillisecondsSinceEpoch(
      messages[index - 1]['timestamp'] ?? DateTime.now().millisecondsSinceEpoch,
    );
    
    // 如果两条消息间隔超过5分钟，显示时间
    final timeDifference = currentTimestamp.difference(previousTimestamp);
    return timeDifference.inMinutes > 5;
  }

  // 格式化消息时间
  String _formatMessageTime(DateTime timestamp) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final messageDate = DateTime(timestamp.year, timestamp.month, timestamp.day);
    
    if (messageDate == today) {
      // 今天：显示时间 HH:mm
      return '${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}';
    } else if (messageDate == today.subtract(const Duration(days: 1))) {
      // 昨天：显示"昨天 HH:mm"
      return '昨天 ${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}';
    } else if (timestamp.year == now.year) {
      // 同年：显示"MM/dd HH:mm"
      return '${timestamp.month}/${timestamp.day} ${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}';
    } else {
      // 不同年：显示"yyyy/MM/dd HH:mm"
      return '${timestamp.year}/${timestamp.month}/${timestamp.day} ${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}';
    }
  }

  // 显示更多操作菜单（黑色气泡样式）
  void _showMoreOptions(BuildContext context, Offset buttonPosition, MessageChatController controller) {
    showMenu(
      context: context,
      color: Colors.black, // 黑色背景
      position: RelativeRect.fromLTRB(
        buttonPosition.dx - 140, // 左边界 - 调整为更靠右
        buttonPosition.dy + 40,   // 上边界（按钮下方）- 增加距离
        buttonPosition.dx + 10,   // 右边界 - 延伸到按钮右侧
        buttonPosition.dy + 200,  // 下边界
      ),
      items: [
        PopupMenuItem(
          value: 'delete',
          child: Row(
            children: [
              Icon(Icons.person_remove, color: Colors.white, size: 20), // 白色图标
              SizedBox(width: 12),
              Text('删除好友', style: TextStyle(color: Colors.white)), // 白色文字
            ],
          ),
        ),
        PopupMenuItem(
          value: 'profile',
          child: Row(
            children: [
              Icon(Icons.person, color: Colors.white, size: 20), // 白色图标
              SizedBox(width: 12),
              Text('查看个人主页', style: TextStyle(color: Colors.white)), // 白色文字
            ],
          ),
        ),
      ],
      elevation: 8,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
    ).then((value) async {
      if (value == 'delete') {
        // 🔥 修复：先刷新用户信息，再显示删除好友弹窗（模仿MyApplication2的实现）
        _showDeleteFriendDialogWithRefresh(context, controller);
      } else if (value == 'profile') {
        await controller.viewUserProfile();
      }
    });
  }

  // 🔥 新增：先刷新用户信息，再显示删除好友弹窗（模仿MyApplication2的实现）
  Future<void> _showDeleteFriendDialogWithRefresh(BuildContext context, MessageChatController controller) async {
    try {
      developer.log('🔄 删除好友流程开始：先刷新用户信息');
      
      // 🔥 Step 1: 先刷新用户信息（参考MyApplication2的showPublishUserHomeAndReview调用）
      await controller.refreshUserInfoForDelete();
      
      // 🔥 Step 2: 数据刷新完成后显示弹窗
      developer.log('✅ 用户信息刷新完成，显示删除好友弹窗');
      _showDeleteFriendDialog(context, controller);
      
    } catch (e) {
      developer.log('💥 刷新用户信息失败: $e');
      ToastUtil.error('获取用户信息失败，请重试');
    }
  }
  
  // 显示删除好友弹窗（使用真实用户数据）
  void _showDeleteFriendDialog(BuildContext context, MessageChatController controller) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Obx(() {
        final userData = controller.fullUserData.value; // 🔥 优先使用API获取的最新数据
        final chatUser = controller.chatUser; // 🔥 作为备选数据
        final activities = controller.userActivities; // 获取真实的活动数据
        
        return DeleteFriendDialog(
          // 🔥 修复数据优先级：优先使用API获取的最新userData（模仿MyApplication2）
          userName: userData?.username ?? chatUser?.name ?? "未知用户",
          userAvatar: userData?.userAvatarUrl ?? chatUser?.avatarUrl ?? "",
          userLocation: userData?.userFrequentPlaces ?? userData?.userCity ?? 
                       chatUser?.userFrequentPlaces ?? chatUser?.userCity ?? "未知",
          userAge: "${userData?.userAge ?? chatUser?.userAge ?? 0}",
          userGender: userData?.userGender ?? chatUser?.userGender ?? "未知",
          userSignature: userData?.userSignature ?? chatUser?.userSignature ?? "这个人很懒，什么都没留下",
          userLikes: userData?.userLikes ?? chatUser?.userLikes ?? 0,
          userFollowers: userData?.userFollowers ?? chatUser?.userFollowers ?? 0,
          userPoints: userData?.userPoints ?? chatUser?.userPoints ?? 0, // 🔥 新增：传递积分用于计算等级
          userTags: userData?.userTags ?? chatUser?.userTags ?? [],
          userActivities: activities, // 传递真实的活动数据
          isLoading: controller.isLoadingUserInfo.value,
          isDeletingFriend: controller.isDeletingFriend.value,
          onDeleteConfirm: () {
            controller.deleteFriend();
          },
          onClearHistory: () {
            controller.clearChatHistory();
          },
        );
      }),
    );
  }

  // 构建聊天气泡（支持真实头像显示）
  /// 🔥 构建消息气泡（支持不同类型消息的显示）
  Widget _buildMessageBubble(bool isMe, String message, MessageChatController controller, {String messageType = 'chat'}) {
    // 🔥 根据消息类型确定样式
    Color bubbleColor;
    Color textColor;
    IconData? systemIcon;
    
    switch (messageType) {
      case 'friend_request':
        // 好友申请消息 - 使用绿色系
        bubbleColor = Colors.green.shade100;
        textColor = Colors.green.shade800;
        systemIcon = Icons.person_add;
        break;
      case 'activity_request':
        // 活动申请消息 - 使用橙色系
        bubbleColor = Colors.orange.shade100;
        textColor = Colors.orange.shade800;
        systemIcon = Icons.event;
        break;
      case 'chat':
      default:
        // 普通聊天消息 - 保持原样式
        bubbleColor = isMe ? const Color(0xFFD94841) : Colors.white;
        textColor = isMe ? Colors.white : Colors.black;
        systemIcon = null;
        break;
    }
    
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
      child: Row(
        mainAxisAlignment: isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 对方头像（仅在对方消息时显示）
          if (!isMe) ...[
            Builder(
              builder: (context) {
                final avatarUrl = controller.chatUser?.avatarUrl ?? '';
                final hasAvatar = avatarUrl.isNotEmpty;
                return CircleAvatar(
                  radius: 16,
                  backgroundColor: Colors.grey[300],
                  backgroundImage: hasAvatar ? CachedNetworkImageProvider(avatarUrl) : null,
                  child: hasAvatar ? null : const Icon(Icons.person, color: Colors.grey, size: 20),
                );
              },
            ),
            const SizedBox(width: 8),
          ],
          
          // 消息气泡（根据消息类型显示不同样式）
          Flexible(
            child: Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(Get.context!).size.width * 0.7, // 最大宽度为屏幕宽度的70%
              ),
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              decoration: BoxDecoration(
                color: bubbleColor,
                borderRadius: BorderRadius.circular(18),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 3,
                    offset: const Offset(0, 1),
                  ),
                ],
                // 🔥 系统消息添加边框
                border: messageType != 'chat' ? Border.all(
                  color: messageType == 'friend_request' ? Colors.green.shade300 : Colors.orange.shade300,
                  width: 1.0,
                ) : null,
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 🔥 系统消息显示图标
                  if (systemIcon != null) ...[
                    Icon(
                      systemIcon,
                      size: 18,
                      color: textColor,
                    ),
                    const SizedBox(width: 8),
                  ],
                  // 消息文本
                  Flexible(
                    child: Text(
                      message,
                      style: TextStyle(
                        color: textColor,
                        fontSize: 16,
                        fontWeight: messageType != 'chat' ? FontWeight.w500 : FontWeight.normal, // 系统消息加粗
                      ),
                      softWrap: true, // 允许文本换行
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          // 自己的头像（仅在自己消息时显示，使用真实头像）
          if (isMe) ...[
            const SizedBox(width: 8),
            Obx(() => CircleAvatar(
              radius: 16,
              backgroundColor: Colors.grey,
              backgroundImage: (controller.currentUserAvatar.value.isNotEmpty)
                  ? CachedNetworkImageProvider(controller.currentUserAvatar.value)
                  : null,
              child: (controller.currentUserAvatar.value.isEmpty)
                  ? const Icon(Icons.person, color: Colors.white, size: 20)
                  : null,
            )),
          ],
        ],
      ),
    );
  }

  // 构建消息输入区域
  Widget _buildMessageInput(MessageChatController controller) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      color: Colors.white,
      child: Row(
        children: [
          // 输入框
          Expanded(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(24),
              ),
              child: TextField(
                controller: controller.messageController,
                decoration: const InputDecoration(
                  hintText: '请输入消息...',
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(vertical: 10),
                ),
                maxLines: 1,
              ),
            ),
          ),
          
          // 发送按钮
          Container(
            margin: const EdgeInsets.only(left: 8),
            decoration: const BoxDecoration(
              shape: BoxShape.circle,
              color: Color(0xFFD94841),
            ),
            child: IconButton(
              icon: const Icon(Icons.send, color: Colors.white),
              onPressed: () => controller.sendMessage(),
            ),
          ),
        ],
      ),
    );
  }

  // 主视图
  Widget _buildView(MessageChatController controller) {
    return Column(
      children: [
        // 聊天消息列表
        Expanded(
          child: Obx(() {
            // 显示加载状态
            if (controller.isLoading.value && (controller.messagesFromService?.isEmpty ?? true)) {
              return const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(height: 16),
                    Text('正在加载聊天记录...'),
                  ],
                ),
              );
            }
            
            // 🔥 修复：正确观察消息列表的响应式变化
            final messages = controller.messagesFromService;
            
            // 🔥 调试日志：打印UI观察到的状态
            try {
              print('🔍 [UI调试] messagesFromService状态检查:');
              print('   - messages == null: ${messages == null}');
              if (messages != null) {
                print('   - messages.length: ${messages.length}');
                print('   - messages类型: ${messages.runtimeType}');
                if (messages.isNotEmpty) {
                  print('   - 第一条消息: ${messages[0]}');
                }
              }
            } catch (e) {
              print('💥 [UI调试] 状态检查异常: $e');
            }
            
            if (messages == null) {
              return const Center(
                child: Text(
                  '正在连接消息服务...',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 16,
                  ),
                ),
              );
            }
            
            // 🔥 确保响应式更新 - 显式访问RxList的length触发观察
            final messageCount = messages.length;
            if (messageCount == 0) {
              return const Center(
                child: Text(
                  '暂无聊天记录\n下拉可刷新',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 16,
                  ),
                ),
              );
            }
            
            return ListView.builder(
              controller: controller.scrollController,
              reverse: false, // 正序显示，最新消息在底部
              padding: const EdgeInsets.symmetric(vertical: 8),
              itemCount: messageCount,
              itemBuilder: (context, index) {
                final messageData = messages[index];
                final content = messageData['content']?.toString() ?? '';
                final isMe = messageData['isMe'] == true;
                final timestamp = DateTime.fromMillisecondsSinceEpoch(
                  messageData['timestamp'] ?? DateTime.now().millisecondsSinceEpoch,
                );
                
                final showTime = index == 0 || _shouldShowTimestamp(index, messages);
                
                return Column(
                  children: [
                    // 时间戳（条件显示）
                    if (showTime)
                      Container(
                        margin: const EdgeInsets.symmetric(vertical: 8),
                        child: Text(
                          _formatMessageTime(timestamp),
                          style: const TextStyle(
                            color: Colors.grey,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    // 消息气泡（根据消息类型显示不同样式）
                    _buildMessageBubble(
                      isMe, 
                      content, 
                      controller,
                      messageType: messageData['messageType'] ?? 'chat', // 🔥 传递消息类型
                    ),
                  ],
                );
              },
            );
          }),
        ),
        
        // 消息输入区域
        _buildMessageInput(controller),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // 设置状态栏样式
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
    ));

    // 🔥 获取控制器tag
    final String controllerTag = _getControllerTag();
    
    return GetBuilder<MessageChatController>(
      init: MessageChatController(),
      tag: controllerTag, // 🔥 使用tag确保控制器实例隔离
      builder: (controller) {
        // 🔥 直接使用GetBuilder传入的controller实例，避免重复获取
        
        return Scaffold(
          backgroundColor: const Color(0xFFEFEFEF), // 浅灰色背景
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            centerTitle: true,
            leading: IconButton(
                icon: const Icon(
                  Icons.arrow_back_ios,
                  color: Colors.black87,
                  size: 20,
                ),
                onPressed: () => Get.back(),
              ),
            title: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  controller.chatUser?.name ?? "聊天",
                  style: const TextStyle(
                    color: Colors.black,
                    fontSize: 19,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                // 🔥 新消息提示UI已移除
              ],
            ),
            actions: [
              // 更多选项按钮（三根横线）
              Builder(
                builder: (context) => IconButton(
                  icon: const Icon(Icons.menu, color: Colors.black), // 改为三根横线图标
                  onPressed: () {
                    // 获取按钮位置
                    final RenderBox button = context.findRenderObject() as RenderBox;
                    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
                    final Offset buttonPosition = button.localToGlobal(Offset.zero, ancestor: overlay);
                    
                    _showMoreOptions(context, buttonPosition, controller);
                  },
                ),
              ),
            ],
          ),
          body: SafeArea(
            child: Stack(
              children: [
                _buildView(controller),
                // 回到底部按钮（修复：使用Obx处理RxBool）
                Obx(() {
                  if (!controller.showScrollToBottomButton.value) {
                    return const SizedBox.shrink();
                  }
                  
                  return Positioned(
                    right: 16,
                    bottom: 80, // 位于输入框上方
                    child: FloatingActionButton(
                      mini: true,
                      backgroundColor: const Color(0xFFD94841),
                      onPressed: () {
                        try {
                          controller.scrollToBottom(animated: true);
                        } catch (e) {
                          // 静默处理异常
                        }
                      },
                      child: const Icon(
                        Icons.keyboard_arrow_down,
                        color: Colors.white,
                        size: 24,
                      ),
                    ),
                  );
                }),
              ],
            ),
          ),
        );
      },
    );
  }
}
